package com.hall.weaponenhancement.service;

import com.hall.util.IdWorker;
import com.hall.weaponenhancement.aggr.GoldAccount;
import com.hall.weaponenhancement.aggr.PlayerGoldAccounts;
import com.mbrs.aggr.MyUserBan;
import com.mbrs.service.LoginOrRegisterResult;
import com.mbrs.service.PairProcessResult;
import dml.accounting.proc.AccountingProcesses;
import dml.accounting.repo.AccountRepository;
import erp.annotation.Process;
import erp.mongodb.MongodbRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GoldService {

    private AccountRepository<GoldAccount, Long> goldAccountRepository;

    @Autowired
    private MongodbRepository<PlayerGoldAccounts, Long> playerGoldAccountsRepository;

    private AccountingProcesses accountingProcesses;

    private IdWorker worker = new IdWorker(1, 1, 1);

    @Autowired
    public GoldService(
            AccountRepository<GoldAccount, Long> goldAccountRepository) {
        this.goldAccountRepository = goldAccountRepository;
        accountingProcesses = new AccountingProcesses(goldAccountRepository);
    }

    //    @Process(listening = "com.mbrs.service.LoginService.loginOrRegister", publish = true)
    @Process
    public void initGoldAccountsForNewPlayer(
            PairProcessResult<MyUserBan, LoginOrRegisterResult> loginOrRegisterResult) {
        LoginOrRegisterResult lgnRslt = loginOrRegisterResult.getB();
        PlayerGoldAccounts playerGoldAccounts = playerGoldAccountsRepository
                .find((Long) lgnRslt.getUser().getId());
        if (playerGoldAccounts != null) {
            return;
        }

        GoldAccount sysGoldAccount = new GoldAccount(worker.nextId(), "0");
        sysGoldAccount.setOwner(0);
        sysGoldAccount.setPlayerId((long) lgnRslt.getUser().getId());
        goldAccountRepository.put(sysGoldAccount);

        GoldAccount userGoldAccount = new GoldAccount(worker.nextId(), "0");
        userGoldAccount.setOwner(1);
        userGoldAccount.setPlayerId((long) lgnRslt.getUser().getId());
        goldAccountRepository.put(userGoldAccount);

        playerGoldAccounts = new PlayerGoldAccounts();
        playerGoldAccounts.setId((long) lgnRslt.getUser().getId());
        playerGoldAccounts.setSysAccountId((long) sysGoldAccount.getId());
        playerGoldAccounts.setUserAccountId((long) userGoldAccount.getId());
        playerGoldAccountsRepository.put(playerGoldAccounts);

        accountingProcesses.transferAnyway(
                playerGoldAccounts.getSysAccountId(),
                playerGoldAccounts.getUserAccountId(), "1000");

    }
}
